package com.bidcms.web.index;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.bidcms.dao.featureMapper;
import com.bidcms.dao.feature_classMapper;
import com.bidcms.dao.goodsMapper;
import com.bidcms.domain.feature;
import com.bidcms.domain.feature_class;
import com.bidcms.domain.goods;
import com.bidcms.util.JsonToFile;
import com.bidcms.util.View2Url;
import com.bidcms.web.BaseController;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import freemarker.template.SimpleScalar;

@Controller("index.PageController")
public class PageController extends BaseController {

	@Autowired
	private featureMapper featureDao;

	@Autowired
	private goodsMapper goodsDao;
	
	@Autowired
	private feature_classMapper featureClassDao;

	// 请求分发器
	@RequestMapping(value = { "index", "/" }, method = RequestMethod.GET)
	public ModelAndView index(HttpServletRequest req, HttpServletResponse resp,
			String con, String act, Integer id) {
		con = con == null ? "index" : con;
		act = act == null ? "index" : act;

		switch (View.getView((con + "_" + act).toUpperCase())) {
		case SHOWCASE_INDEX:
			return SHOWCASE_INDEX(req, resp);
		case SHOWCASE_FCATEGORY:
			return SHOWCASE_FCATEGORY(req, resp);
		case SHOWCASE_COMPONENT:
			return SHOWCASE_COMPONENT(req, resp);
		case SHOW_FEATURE:
			return SHOW_FEATURE(req, resp, id);
		case SHOW_FCATEGORY:
			return SHOW_FCATEGORY(req, resp, id);
		default:
			return SHOWCASE_INDEX(req, resp);
		}
	}

	public ModelAndView SHOWCASE_COMPONENT(HttpServletRequest req,
			HttpServletResponse resp) {
		ModelAndView mv = new ModelAndView("showcase_component");
		addGlobalAttrs(mv);
		mv.addObject("View2Url", new View2Url());
		return mv;
	}

	public ModelAndView SHOWCASE_FCATEGORY(HttpServletRequest req,
			HttpServletResponse resp) {
		ModelAndView mv = new ModelAndView("showcase_fcategory");
		mv.addObject("View2Url", new View2Url());
		addGlobalAttrs(mv);
		return mv;
	}

	public ModelAndView SHOW_FEATURE(HttpServletRequest req,
			HttpServletResponse resp, Integer id) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("View2Url", new View2Url());
		addGlobalAttrs(mv);
		feature f = featureDao.selectByPrimaryKey(id);
		JsonParser jsonp = new JsonParser();
		JsonArray jsonarr = (JsonArray) jsonp.parse(JsonToFile.getfeaturejson(
				id.toString(), getRealPath(req, "/data")));
		JsonObject data1 = (JsonObject) jsonarr.get(0);
		JsonObject data2 = (JsonObject) jsonarr.get(1);
		String type = data2.get("type").getAsString();
		String templateJ = data1.get("template") == null ? "" : data1.get(
				"template").getAsString();
		String template = StringUtils.hasText(templateJ) ? templateJ : (type
				.equals("scroll") || type.equals("scroll_nav") ? type
				: "normal");
		List<String> viewTypes = new ArrayList<String>();
		viewTypes.add("fbb");
		viewTypes.add("weixin");
		viewTypes.add("scroll");
		viewTypes.add("scroll_nav");
		if (StringUtils.isEmpty(template)) {
			mv.setViewName("tpl/noTemplate");
		} else {
			if (!viewTypes.contains(template)) {// 不是默認模板分类
				mv.addObject("components", parseComponents(jsonarr));
			}
			/*
			 * $_global['mp_data']['logo']=$shop['logo'];
			 * $_global['mp_data']['intro']=$shop['intro'];
			 * $_global['mp_data']['team_name']=$shop['shop_name'];
			 */
			// $pagetitle=$info['title'];
			mv.addObject("pagetitle", f.getTitle());
			JsonObject share = new JsonObject();
			share.addProperty("title", f.getTitle());
			share.addProperty("desc", "");
			share.addProperty("cover", "");// 'cover'=>$shop['logo']
			share.addProperty("link", "");
			SimpleScalar ss = getFreeMarkerVar("webRoot");
			mv.addObject("webRoot", ss.getAsString());
			mv.addObject("share", ss + "/index?con=show&act=feature&id="
					+ f.getId().toString());
			mv.addObject("id", f.getId());
			StringBuilder viewName = new StringBuilder("tpl/");
			viewName.append(template);
			viewName.append("/index");
			mv.addObject("dataJson", jsonarr);
			mv.setViewName(viewName.toString());
		}
		return mv;

	}

	public ModelAndView SHOWCASE_INDEX(HttpServletRequest req,
			HttpServletResponse resp) {
		ModelAndView mv = new ModelAndView("showcase_feature");
		mv.addObject("View2Url", new View2Url());
		addGlobalAttrs(mv);

		return mv;
	}

	public JsonArray parseComponents(JsonArray clone) {
		JsonParser jp = new JsonParser();
		JsonArray components = (JsonArray) jp.parse(clone.toString());
		for (int i = 0; i < components.size(); i++) {
			JsonObject item = (JsonObject) components.get(0);
			if (item.get("type").getAsString().equals("goods_list")) {
				if (((JsonObject) item.get("goods")).get("type").getAsString()
						.equals("tag")) {
					Integer num = item.get("").getAsInt() > 0 ? item.get("")
							.getAsInt() : 6;
					Integer id = ((JsonObject) item.get("")).get("id")
							.getAsInt();
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("id", id);
					params.put("num", num);
					List<goods> goods = goodsDao.queryPage(params);
					JsonArray goodsJ = new JsonArray();
					for (goods good : goods) {
						JsonObject jsongood = new JsonObject();
						jsongood.addProperty("id", good.getId());
						jsongood.addProperty("title", good.getTitle());
						jsongood.addProperty("image_url", good.getImageUrl());
						jsongood.addProperty("price", good.getPrice());
						goodsJ.add(jsongood);
					}
					item.add("list", goodsJ);
				}
			}

			if (item.get("type").getAsString().equals("tag_list")) {
				JsonArray sub_entry = (JsonArray) item.get("sub_entry");
				for (int idx = 0; idx < sub_entry.size(); idx++) {
					JsonObject se = (JsonObject) sub_entry.get(0);
					if (se.get("type").getAsString().equals("tag")) {
						int id = se.get("id").getAsInt();
						Map<String, Object> params = new HashMap<String, Object>();
						params.put("id", id);
						params.put("num", 4);
						List<goods> goods = goodsDao.queryPage(params);
						JsonArray goodsJ = new JsonArray();
						for (goods good : goods) {
							JsonObject jsongood = new JsonObject();
							jsongood.addProperty("id", good.getId());
							jsongood.addProperty("title", good.getTitle());
							jsongood.addProperty("image_url",
									good.getImageUrl());
							jsongood.addProperty("price", good.getPrice());
							goodsJ.add(jsongood);
						}
						se.add("list", goodsJ);

					}
				}

			}

		}
		System.out.println(components);
		return components;
	}
	
	public ModelAndView SHOW_FCATEGORY(HttpServletRequest req,
			HttpServletResponse resp, Integer id) {
		Object psO= req.getParameter("ps");
		Integer ps = psO==null?320:Integer.valueOf((String)psO);
		ModelAndView mv =new ModelAndView("show_fcategory");
		mv.addObject("ps", ps);
		addGlobalAttrs(mv);
		SimpleScalar ss = getFreeMarkerVar("webRoot");
		mv.addObject("webRoot", ss.getAsString());
		mv.addObject("id", id);
		feature_class fc = featureClassDao.selectByPrimaryKey(id);
		if(fc!=null){
			JsonParser jp = new JsonParser();
			mv.addObject("pagetitle", fc.getTitle());
			JsonArray fileJson = (JsonArray) jp.parse(JsonToFile.getfeature_classjson(id.toString(), getRealPath(req, "/data")));
			mv.addObject("dataJson",fileJson);
			mv.addObject("info", fc);
			mv.addObject("components", parseComponents(fileJson));
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("category", fc.getId());
			List<feature> fs = featureDao.findByMap(params);
			mv.addObject("list", fs);
			mv.addObject("shopId", 1);
		}
		return mv;
	}
}
